angular.module('CheckTransfer')
    .factory('CheckTransfer.CheckService', ['$q', '$cordovaVibration', 'Http', 'imanDialog', 'Config',
        function ($q, $cordovaVibration, Http, imanDialog, Config) {
            var o = {},
                container = {},
                validBarcodeList = [],
                department = {},
                wareHouse = {},
                requestList = {},
                scanQualifiedObj = {},
                rcvRecordList = {},
                scanUnQualifiedArray = [],
                scanBarcode = {},
                choice = '',
                selectCode = '',
                count = {
                    total: 0,
                    concession: 0,
                    extra: 0,
                    qualified: 0,
                    unQualified: 0
                },
                isUpdateMsg = true;
            o.setScanBarcode = function (barcode) {
                scanBarcode[barcode] = barcode;
            };
            /**
             * 判断是不是重复扫描
             * @param barcode
             */
            o.scanRepeat = function (barcode) {
                return scanBarcode.hasOwnProperty(barcode);
            };

            /**
             * 获取部门列表
             * @returns {*}
             */
            o.queryDepartment = function (wareHouseId) {
                var defer = $q.defer();
                Http.post({
                    url: '/api/Kanban/getAllDepartment',
                    data: {
                        Parameter: {
                            wareHouseId: wareHouseId
                        }
                    }
                }).then(function (res) {
                    // department = {};
                    angular.forEach(res, function (obj) {
                        department[obj.DemandDepartment.Code] = obj;
                    });
                    defer.resolve(res);
                }, function (err) {
                    defer.reject(err);
                });
                return defer.promise;
            };

            o.queryWHouse = function () {
                var defer = $q.defer();
                Http.post({
                    url: '/api/Kanban/getAllWareHouse'
                }).then(function (res) {
                    angular.forEach(res, function (obj) {
                        if (!wareHouse.hasOwnProperty(obj.Code)) {
                            wareHouse[obj.Code] = obj;
                        }
                    });
                    defer.resolve(res);
                }, function (err) {
                    defer.reject(err);
                });
                return defer.promise;
            };

            /**
             * 根据barcode获取主档信息
             * @param barcode
             * @returns {*}
             */
            o.queryBarcodeMaster = function (barcode) {
                var defer = $q.defer();
                Http.post({
                    url: '/api/barcode/findBarcodeMaster',
                    data: {
                        Parameter: {
                            Barcode: barcode
                        }
                    }
                }).then(function (res) {
                    defer.resolve(res);
                }, function (err) {
                    // delete scanBarcode[barcode];
                    defer.reject(err);
                });
                return defer.promise;
            };

            /**
             * 根据主档信息获取容器信息
             * @param barcodeInfo
             * @returns {*}
             */
            o.queryContainer = function (barcodeInfo) {
                var defer = $q.defer();
                Http.post({
                    url: '/api/Kanban/getContainer',
                    data: {
                        Parameter: {
                            entityId: barcodeInfo.EntityID //容器ID
                        }
                    }
                }).then(function (info) {
                    container = info;
                    defer.resolve(info);
                }, function (err) {
                    defer.reject(err);
                });
                return defer.promise;
            };

            /**
             * 数据拼接处理
             * @param info
             */
            o.arrangeData = function (info) {
                if (scanBarcode.hasOwnProperty(info.Barcode)) {
                    imanDialog.toastBottom("重复扫描");
                    isVibrate();
                    return false;
                } else {
                    scanBarcode[info.Barcode] = info.Barcode;
                    var key = info.ItemMaster.Code + '-' + (info.DescSeg1 ? info.DescSeg1 : '空') + '-' + (info.DescSeg2 ? info.DescSeg2 : '空');
                    count.total++;
                    if (rcvRecordList.hasOwnProperty(info.Barcode)) {
                        if (info.QCStatus === 0) {
                            if (requestList.hasOwnProperty(key) && requestList[key].demandNum > scanQualifiedObj[key].checkNum) {
                                count.qualified++;
                                validBarcodeList.push(info.Barcode);

                                if (scanQualifiedObj.hasOwnProperty(key)) {
                                    scanQualifiedObj[key].checkNum += 1;
                                } else {
                                    scanQualifiedObj[key] = {
                                        key: key + '(' + 0 + ')',
                                        itemMasterCode: info.ItemMasterCode,
                                        checkNum: 1,
                                        scanStatus: 'green'
                                    };
                                }

                            } else {
                                isVibrate();
                                count.extra++;
                                if (scanQualifiedObj.hasOwnProperty(key)) {
                                    scanQualifiedObj[key].checkNum += 1;
                                } else {
                                    scanQualifiedObj[key] = {
                                        key: key + '(' + 0 + ')',
                                        itemMasterCode: info.ItemMasterCode,
                                        checkNum: 1,
                                        scanStatus: 'grey'
                                    };
                                }
                                imanDialog.toastBottom("物料不在下游要货范围内");
                            }
                        } else if (info.QCStatus === 2) {
                            validBarcodeList.push(info.Barcode);
                            count.concession++;
                            if (scanQualifiedObj.hasOwnProperty(key)) {
                                scanQualifiedObj[key].checkNum += 1;
                            } else {
                                scanQualifiedObj[key] = {
                                    key: key + '(' + 0 + ')',
                                    itemMasterCode: info.ItemMasterCode,
                                    checkNum: 1,
                                    scanStatus: 'yellow'
                                };
                            }
                        } else if (info.QCStatus === 1 || info.QCStatus === 3 || info.QCStatus === 4 || info.QCStatus === 5) {
                            if (info.QCStatus === 5) {
                                imanDialog.toastBottom("物料报废");
                            } else if (info.QCStatus === 1) {
                                imanDialog.toastBottom("物料不合格");
                            }
                            isVibrate();
                            count.unQualified++;
                            scanUnQualifiedArray.push({
                                ItemMasterCode: info.ItemMasterCode,
                                Barcode: info.Barcode
                            });
                        }
                    } else {
                        isVibrate();
                        count.extra++;
                        // if (scanQualifiedObj.hasOwnProperty(key)) {
                        //     scanQualifiedObj[key].checkNum += 1;
                        // } else {
                        //     scanQualifiedObj[key] = {
                        //         key: key + '(' + 0 + ')',
                        //         itemMasterCode: info.ItemMasterCode,
                        //         checkNum: 1,
                        //         scanStatus: 'grey'
                        //     };
                        // }
                        imanDialog.toastBottom("入库记录不存在这个物料");
                    }
                    return true;
                }
            };

            /**
             * 查询看板信息
             * @param departmentId
             * @returns {*}
             */
            o.queryKanBanMsg = function (departmentId) {
                var defer = $q.defer();
                Http.post({
                    url: '/api/Kanban/getKanbanDemandInfo',
                    data: {
                        Parameter: {
                            demandDepartment: departmentId
                        }
                    }
                }).then(function (demands) {
                    var localObj = {};
                    angular.forEach(demands, function (demand) {
                        var num = demand.TotalDemandQty - demand.TotalStockQty;
                        var keys = demand.ItemMaster.Code + '-' + (demand.DescSeg1 ? demand.DescSeg1 : '空') + '-' + (demand.DescSeg2 ? demand.DescSeg2 : '空');
                        localObj[keys] = {
                            key: keys + '(' + num + ')',
                            itemMasterCode: demand.ItemMaster.Code,
                            hashKey: keys,
                            demandNum: num,
                            checkNum: 0
                        };
                    });
                    defer.resolve(localObj);
                }, function (err) {
                    defer.reject(err);
                });
                return defer.promise;
            };

            o.getRcvTime = function (res) {
                var defer = $q.defer();
                Http.post({
                    url: '/api/produceWork/queryRcvRecordsByBarcodeMaster',
                    data: {
                        Parameter: {
                            barcodeMaster: res._id //barcodeMaster
                        }
                    }
                }).then(function (result) {
                    if (!result || !result.RcvDateTime) {
                        defer.resolve({
                            d: 0,
                            h: 0,
                            mf: 0
                        });
                        return;
                    }
                    var milliseconds = Date.now() - new Date(result.RcvDateTime).valueOf();
                    var ms = milliseconds / 1000 / 60;
                    var m = ms % 60;
                    var mf = Math.round(m);
                    var h = ((ms - m) / 60) % 24;
                    var d = (((ms - m) / 60) - ((ms - m) / 60) % 24) / 24;
                    defer.resolve({
                        d: d,
                        h: h,
                        mf: mf
                    });
                }, function (err) {
                    defer.reject(err);
                });
                return defer.promise;
            };

            o.setCount = function (obj) {
                count = obj;
            };

            o.getCount = function () {
                return count;
            };

            o.setScanQualifiedObj = function (res) {
                requestList = {};
                scanQualifiedObj = {};
                angular.forEach(res, function (obj) {
                    scanQualifiedObj[obj.hashKey] = obj;
                    requestList[obj.hashKey] = obj;
                });
                //scanQualifiedObj = angular.copy(obj);
                //requestList = angular.copy(obj);
            };

            o.getScanQualifiedObj = function () {
                return scanQualifiedObj;
            };

            o.getScanUnQualifiedArray = function () {
                return scanUnQualifiedArray;
            };

            o.getContainer = function () {
                return container;
            };

            o.setContainer = function () {
                container = {};
            };
            o.getValidBarcodeList = function () {
                return validBarcodeList;
            };

            o.setDepartChoice = function (code) {
                if (choice === code) {
                    isUpdateMsg = false;
                } else {
                    isUpdateMsg = true;
                }
                choice = code;
            };

            o.getChoice = function () {
                return choice;
            };

            o.getIsUpdateMsg = function () {
                return isUpdateMsg;
            };

            o.getDepart = function (code) {
                return department[code];
            };

            o.setSelectCode = function (code) {
                selectCode = code;
            };
            o.getSelectCode = function () {
                return selectCode;
            };

            o.getWareHouse = function (code) {
                if (code) {
                    return wareHouse[code];
                } else {
                    return wareHouse;
                }

            };

            o.resetDefault = function () {
                validBarcodeList = [];
                requestList = {};
                scanQualifiedObj = {};
                scanUnQualifiedArray = [];
                scanBarcode = {};
                rcvRecordList = {};
                count = {
                    total: 0,
                    concession: 0,
                    extra: 0,
                    qualified: 0,
                    unQualified: 0
                };
                isUpdateMsg = false;
                choice = '';
            };

            function isVibrate() {
                if (typeof cordova !== 'undefined') {
                    $cordovaVibration.vibrate(1000);
                }
            }

            o.BarcodeIsExistRcvRecord = function () {
                var defer = $q.defer();
                Http.post({
                    url: '/api/barcode/queryRcvRecords',
                    data: {
                        WareHouseId: Config.get('wareHouse')._id
                    }
                }).then(function (res) {
                    angular.forEach(res, function (s) {
                        rcvRecordList[s.Barcode] = s.Barcode;
                    });
                }, function (err) {
                    defer.reject(err);
                });
                return defer.promise;
            };

            return o;
        }
    ])
;
